import type { SpriteRect } from './Types';

const getSpriteStyles = (
    _pxReference: number,
    image: string,
    spriteList: SpriteRect[],
    containerWidth: number,
    containerHeight: number,
    fitMode: string
): string[] => {
    const styleMap = [];
    let transStyle = '';
    for (let i = 0; i < spriteList.length; i++) {
        const sprite = spriteList[i];
        const width = sprite.w / _pxReference; // 基值转换
        const height = sprite.h / _pxReference; // 基值转换
        // object-fit
        const scaleSize = {
            width: (containerWidth || sprite.w) / sprite.w, // 缩放后的宽度
            height: (containerHeight || sprite.h) / sprite.h, // 缩放后的高度
        };
        const scaleSizeMin = Math.min(scaleSize.width, scaleSize.height); // 取短边
        const scaleSizeMax = Math.max(scaleSize.width, scaleSize.height); // 取长边
        (fitMode === 'fill' &&
            (transStyle = `transform: scale(${scaleSize.width},${scaleSize.height});`)) || // fill
            (fitMode === 'cover' &&
                (transStyle = `transform: scale(${scaleSizeMax},${scaleSizeMax});`)) || // cover
            (fitMode === 'contain' &&
                (transStyle = `transform: scale(${scaleSizeMin},${scaleSizeMin});`)) || // contain
            (fitMode === 'scale-down' &&
                scaleSizeMin <= 1 &&
                (transStyle = `transform: scale(${scaleSizeMin},${scaleSizeMin});`)); // scale-down
        const targetFileSrc = new URL(
            image,
            import.meta.url?.replace('app.kumiamei', 'activity.kumiamei.com')
        )?.href;
        // 样式入栈
        styleMap.push(
            `width:${width}rem;height:${height}rem;background-position: ${-sprite.x}px ${-sprite.y}px;background-image: url("${targetFileSrc}");${transStyle}`
        );
    }
    return styleMap;
};

export { getSpriteStyles };
